// src/services/SponsorRecordsService.ts

import { BASE_URL } from '@/services/apiConfig';

interface SponsorRecordParams {
  year_from: number;
  year_to: number;
  current?: boolean;
  program_id?: number;
  program_code?: string | string[];
  keyword?: string;
  faculty?: string | string[];
  coop_program?: string | string[];
  page?: number;
  page_size?: number;
}

interface SponsorRecord {
  sponsor_id: number;
  company_code: string;
  company_name: string;
  contacts: unknown[];
  umbrella_code: string | null;
  umbrella_name: string | null;
  program_id: number;
  program_code: string;
  scholarship_years: string;
  latest_year: number;
  status: string;
  program_year: number;
  program_length: number;
  program_value: number;
  faculty: string;
  coop_program: string;
  position: number;
  total_amount_per_position: number;
  sponsorship_cost: number;
  logo: string | null;
  logo_last_updated: string | null;
};

interface SponsorRecordsResponse {
  meta: {
    total: number;
    page: number;
    page_size: number;
  };
  items: SponsorRecord[];
}

export const fetchSponsorRecords = async (
  params: SponsorRecordParams
): Promise<SponsorRecordsResponse> => {
  const token = localStorage.getItem('token');
  if (!token) throw new Error('No token found');

  const query = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null) {
      if (Array.isArray(value)) {
        value.forEach(v => query.append(key, String(v)));
      } else {
        query.append(key, String(value));
      }
    }
  });

  const res = await fetch(`${BASE_URL}/sponsors/records?${query.toString()}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!res.ok) {
    const err = await res.text();
    throw new Error(`Fetch failed: ${res.status} - ${err}`);
  }

  const data: SponsorRecordsResponse = await res.json();
  return data;
};